use std::fs;
use std::fs::File;
// use std::os::windows::fs::MetadataExt;
use crate::{list_directory, program_root};
use async_std::task::block_on;
use image::imageops::FilterType;
use image::{self, GenericImageView};
use image::{DynamicImage, ImageOutputFormat};
use std::path::PathBuf;

pub fn compress_img() {
    let start_time = chrono::Local::now(); //获取结束时间
    let (pic_dir, _) = list_directory::get_directory();
    block_on(async move {
        compress_images(pic_dir);
    });

    let end_time = chrono::Local::now(); //获取结束时间
    let duration_time = end_time.signed_duration_since(start_time).to_std().unwrap(); //耗时
    println!(
        "压缩任务开始时间 : {:?},结束时间 :{:?},耗时:{:?}",
        start_time.format("%Y-%m-%d %H:%M:%S").to_string(),
        end_time.format("%Y-%m-%d %H:%M:%S").to_string(),
        duration_time
    );
    // 返回主菜单
    program_root();
}

fn compress_images(dirs: fs::ReadDir) {
    let exts: Vec<&str> = vec!["png", "jpg", "jpeg"];
    // let mut thread_vec: Vec<std::thread::JoinHandle<()>> = Vec::new();
    for entry in dirs {
        let entry = entry.expect("读取文件夹失败");
        let path = entry.path();
        if path.is_dir() {
            println!("正在遍历处理文件夹: {}", path.display());
            compress_images(fs::read_dir(path).unwrap()); //递归遍历文件夹
        } else {
            let ext = match path.extension() {
                Some(ext) => ext.to_str().unwrap(),
                None => "",
            };
            let f_name = path.to_str().unwrap().to_string();

            if exts.contains(&ext) {
                //根据图片后缀名
                //  如果文件小于5MB 就不处理
                if entry.metadata().unwrap().len() < 5300000 {
                    println!("文件比较小无需处理:  {}", f_name);
                } else {
                    //  扩展名在里面,文件大于5MB才压缩
                    let pic_reader = match image::open(&path) {
                        Ok(img) => img,
                        _ => {
                            println!("图片读取错误:  {}", f_name);
                            return;
                        }
                    };

                    //  多线程处理
                    async_std::task::spawn(async move {
                        com_image(path, f_name, pic_reader).await;
                    });

                    // let handle = thread::spawn(move || {
                    //     com_image(path, f_name, pic_reader);
                    // });
                    // thread_vec.push(handle);
                }
            }
        }
    }

    // for handle in thread_vec {
    //     handle.join().unwrap();
    // }
}

async fn com_image(out_path: PathBuf, f_name: String, pic_reader: DynamicImage) {
    println!("正在处理图片:    {}", f_name);
    let w = pic_reader.width() / 2_u32;
    let h = pic_reader.height() / 2_u32;
    let scaled = pic_reader.resize(w, h, FilterType::Lanczos3);
    let p = out_path.clone();
    let ext = p.extension().unwrap().to_str().unwrap();
    let mut out_put = File::create(out_path).unwrap();
    //  scaled.save(out_path); //保存图片
    if ext == "png" {
        scaled
            .write_to(&mut out_put, ImageOutputFormat::Png)
            .unwrap();
    } else {
        scaled
            .write_to(&mut out_put, ImageOutputFormat::Jpeg(100))
            .unwrap();
    }
}
